<?php
/**
 * AJAX Handler for Twitter: Add - adds a twitter account to a project.
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    $_ECLIPSEMDE = array();
    
    // Disable Templating System
    $_ECLIPSEMDE['TEMPLATING'] = false;
    require_once('../../SiteIncludes.GLOBAL.php');
    
    // Tell libdebug to never print out error information - overrides debugging flags in fwork
    $_LIBDEBUG->silence();
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
    
    // Ensure all variables needed are set
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($gVAR['alias']) !== false && isset($gVAR['account']) !== false) {
	try {
	    $Project =& $ProjectStash->get($gVAR['alias']);
	    if($Project->userCanEdit($_LOGGEDINUSER->get_userid()) === true) {
		$Project->instanciate();
		$twitters = $Project->getTwitters();
		array_push($twitters, ($Project->getTwitterToDisplay()));
		if(in_array($gVAR['account'], $twitters) === false) {
		    $safe_un = $sql_conx->real_escape_string($gVAR['account']);
		    $query = $sql_conx->query("INSERT INTO `tool_twitter` ( `pid` , `username` , `display` ) VALUES ( '{$Project->getID()}',  '{$safe_un}',  '0' );");
		    if($sql_conx->affected_rows === 0) {
			$header = "HTML/1.1 500 Internal Server Error";
			$html_body = <<<EOB
			<script type="text/javascript">
			    parent.EDJXConfirmer.show_nok();
			</script>
EOB;
		    } else {
			$Project->updateTriggered();
			$Project->updateWrite($_LOGGEDINUSER->get_userid(), ($Project->isMaintainer($_LOGGEDINUSER->get_userid()) === true ? ProjectEditType::AddTwitter : ProjectEditType::AdminAddTwitter), array($gVAR['account']));
			$header = "HTML/1.1 200 OK";
			$html_body = <<<EOB
			<script type="text/javascript">
			    parent.EDJXConfirmer.show_ok();
			    parent.TwitterEDJX.invalidAdd_Exists(false);
			</script>
EOB;
		    }
		} else {
		    $header = "HTML/1.1 200 OK";
		    $html_body = <<<EOB
			<script type="text/javascript">
			    parent.EDJXConfirmer.show_nok();
			    parent.TwitterEDJX.invalidAdd_Exists(true);
			</script>
EOB;
		}
		$html_head = <<<EOH
		    <!DOCTYPE html>
			<html>
			    <head><title></title></head>
			    <body>
EOH;
		$html_tail = <<<EOT
			    </body>
			</html>
EOT;
		header($header);
		echo $html_head.$html_body.$html_tail;
		die();
	    } else {
		throw new InvalidProjectException();
	    }
	} catch(InvalidProjectException $e) {
	    header("HTTP/1.1 400 Bad Request");
	    die($nok_caller);
	}
    } else {
	header("HTTP/1.1 400 Bad Request");
	die($nok_caller);
    }
?>